package com.linkage.jz.bankruptcy.activity.Person;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.TokenInfo;
import com.linkage.jz.bankruptcy.fragment.GroupChildrenCollect;
import com.linkage.jz.bankruptcy.fragment.GroupChildrenHasBuy;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.MyCommonDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public  class PersonSettingAboutActivity extends BaseActivity implements OnClickListener{
    private static final String TAG = PersonSettingAboutActivity.class.getSimpleName();
    private MyCommonDialog dialog;
    private ShapeLoadingDialog shapeLoadingDialog ;

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        r_tru.setOnClickListener(this);
        top_back.setOnClickListener(this);
        r_getver.setOnClickListener(this);
        ll_myweb.setOnClickListener(this);
        ll_intro.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_title.setText("关于我们");
        top_mune.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initView() {

    }


    TextView top_title,tv_ver;
    Button top_back,top_mune;
    RelativeLayout r_tru,r_getver;
    private LinearLayout ll_myweb,ll_intro;

    public static void start(Context context) {
        Intent intent = new Intent(context, PersonSettingAboutActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_person_about);

        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        tv_ver.setText("版本 "+Utils.getLocalVersionName(this));

        super.onCreate(savedInstanceState);
    }


    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        r_tru = findViewById(R.id.r_tru);
        r_getver = findViewById(R.id.r_getver);
        tv_ver = findViewById(R.id.tv_ver);
        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);

        ll_myweb = findViewById(R.id.ll_myweb);
        ll_intro = findViewById(R.id.ll_intro);



    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                finish();
                break;
            case R.id.r_tru:
                PersonSettingReadMeActivity.start(this);
                break;

            case R.id.r_getver:
                getVer();
//                getTest();
                break;
            case R.id.ll_myweb:
                showWeb("http://www.poxiao.com");
                break;
            case R.id.ll_intro:
                PersonSettingReadMeActivity.start(this);
                break;

            default:
                break;
        }
    }

    private int update(String url) {
        int ret = -1;
        try {
            Uri uri = Uri.parse(url);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
            ret = 0;
        } catch (Exception e) {

        }
        return ret;
    }


    public void getTest()
    {
        dialog = new MyCommonDialog(
                PersonSettingAboutActivity.this, "新版本提示",
                " 检测到最新版本:" + 1 + "\n "
                        + 1, "取消", "确定更新");
        dialog.setCancelable(false);
        dialog.setOkListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                update("https://www.baidu.com");
            }
        });
        dialog.setCancelListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing())
                    dialog.dismiss();
//                finish();
            }
        });
        dialog.show();
    }
    public void getVer()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        final String verName = Utils.getLocalVersionName(this)+"";
        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)

                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("version", verName)
                .add("type", "0")
                .build();

        String url = Consts.WEBURL_GETAPPVER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(PersonSettingAboutActivity.this,"获取失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    JSONObject data = object.optJSONObject("data");

                    if(object.optInt("code") == 0)
                    {
                        if(data == null)
                        {
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                            Toast.makeText(PersonSettingAboutActivity.this, "当前已经是最新版本", Toast.LENGTH_SHORT).show();
                                }

                            });
//                            return;
                        }else {
                            final String strVer = data.optString("version");
                            final String strNote = data.optString("note");
                            final String strUrl = data.optString("url");

                            if (verName.equalsIgnoreCase(strVer)) {
                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        //更新UI
                                        Toast.makeText(PersonSettingAboutActivity.this, "当前已经是最新版本", Toast.LENGTH_SHORT).show();

                                    }

                                });
                            } else {
                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        //更新UI
                                        dialog = new MyCommonDialog(
                                                PersonSettingAboutActivity.this, "新版本提示",
                                                " 检测到最新版本:" + strVer + "\n "
                                                        + strNote, "取消", "确定更新");
                                        dialog.setCancelable(false);
                                        dialog.setOkListener(new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                update(strUrl);
                                            }
                                        });
                                        dialog.setCancelListener(new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (dialog.isShowing())
                                                    dialog.dismiss();
//                finish();
                                            }
                                        });
                                        dialog.show();
                                    }

                                });
                            }
//                        finish();
                        }

                    }else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(PersonSettingAboutActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(PersonSettingAboutActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    private int showWeb(String url) {
        int ret = -1;
        try {
            Uri uri = Uri.parse(url);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
            ret = 0;
        } catch (Exception e) {

        }
        return ret;
    }


}

